package edu.washington.ling.syntric.consistency;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

import edu.washington.ling.syntric.struct.tree.Token;
import edu.washington.ling.syntric.struct.tree.Tree;

public class UnaccusativeRule extends ConsistencyRule {
	private Set<String> unaccusatives;
	public UnaccusativeRule() throws IOException {
		unaccusatives = new HashSet<String>();
		try {
			File unaccFile = new File("resources", "unaccusatives.txt");
			InputStream is = this.getClass().getResourceAsStream(unaccFile.getPath());
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String line = null;
			while ((line = br.readLine()) != null) {
				if (line.length() > 0) {
					unaccusatives.add(line);
				}
			}
		} catch (IOException e) {
			System.err.println("Could not create unaccusative consistency rule.");
			e.printStackTrace();
			System.exit(0);
		}
	}
	@Override
	public void apply(Tree ds) {
		Token dsRoot = ds.getDSRoot();
		apply(dsRoot, ds);
	}
	public void apply(Token t, Tree ds) {
		for (Token child: t.getDSDependents()) {
			apply(child, ds);
		}
		// Detect if k1- or pof-child is present
		Token k1Child = null, pofChild = null;
		for (Token child: t.getDSDependents()) {
			if (child.getDSRelation().equals("k1")) {
				k1Child = child;
			}
			if (child.getDSRelation().equals("pof")) {
				pofChild = child;
			}
		}
		for (Token child: t.getECDependents()) {
			if (child.getDSRelation().equals("k1")) {
				k1Child = child;
			}
		}
		// Diagnostic test (pt 1)
		if (unaccusatives.contains(t.getWord()) && t.getTag().equals("VM")) {
			t.setFeature("unaccusative", Boolean.toString(true));
			
			// Diagnostic test (pt 2)
			if (k1Child != null || (pofChild != null && k1Child == null)) {
			
				// Get index for new EC
				int index = ds.nextCoindex();
			
				// Create a CASE ec and attach
				// to verb with k2 relation
				Token ec = ConsistencyUtils.createMovementEC("CASE", "k2", index);
			
				// Add ec to verb
				t.addECDependent(ec);
				if (k1Child != null) {
					// Set target index of k1-child
					k1Child.setDSTargetIndex(index);
				}
				else if (pofChild != null) {
					// Or set target index of pof-child
					pofChild.setDSTargetIndex(index);
				}
			}
		}
	}
}